<template>
  <el-select
    v-model="currentID"
    filterable
    :placeholder="placeholder"
    clearable
    @change="handleChange"
    :disabled="disabled"
  >
    <el-option
      v-for="item in deptOptions"
      :key="item.deptId"
      :label="item.deptName"
      :value="item[valueKey]"
    ></el-option>
  </el-select>
</template>

<script>
import { listDept } from "@/api/system/dept";
import { getCompany } from "@/api/company/company";

export default {
  props: {
    defaultValue: {
      type: Number | String,
    },
    valueKey: {
      type: String,
      default: 'deptId'
    },
    // 单位ID,筛选部门
    comId: {
      type: Number | String,
    },
    placeholder: {
      type: String,
      default: "请选择部门",
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    defaultValue(nval) {
      this.currentID = nval;
    },
    comId(nval) {
      if(nval){
        getCompany(nval).then((res) => {
          this.deptParams.parentId = res.data.deptId;
          this.getListDept()
        });
      }else{
        this.deptParams.parentId = null;
        this.getListDept()
      }
    },
  },
  data() {
    return {
      currentID: null,
      deptOptions: [],
      deptParams: {
        saasType: 3,
        parentId: null,
      },
      loading: false,
    };
  },
  async created() {
    if(this.comId){
      const { data } = await getCompany(this.comId);
      this.deptParams.parentId = data.deptId;
    }
    this.currentID = this.defaultValue;
    this.getListDept();
  },
  methods: {
    /** 查询部门下拉树结构 */
    async getListDept() {
      const { data } = await listDept(this.deptParams);
      this.deptOptions = data;
      if(this.currentID){
        const findIndex = data.findIndex(v=> v.deptId === this.currentID);
        if(findIndex === -1){
          this.currentID = null;
          this.handleChange(null);
        }
      }
    },
    handleChange(e) {
      this.$emit("change", e);
    },
  },
};
</script>

<style lang="scss" scoped></style>
